package net.yebaihe.wc;

import java.io.IOException;
import java.util.HashMap;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class OfflineDataMan extends DataMan {

	@Override
	protected void SendNormalRequest(MSGTYPE msgType, HashMap<String, String> params) {
		switch (msgType){
		case LOGIN:
			dologin(params);
			break;
		case REGISTER:
			doregister(params);
			break;
		case UPDATE_IMAGE:
			doupdateimg(params);
			break;
		}
	}

	private void doupdateimg(HashMap<String, String> params) {
		SQLiteDatabase db = MyHelper.get(machine).getReadableDatabase();
		if (db!=null){
			ContentValues initValues = new ContentValues();
			try {
				initValues.put("image",Base64.decode(params.get("image")));
				db.update("users", initValues, "email='"+params.get("email")+"'", null);
				machine.HandleMessage(MSGTYPE.UPDATE_IMAGE, true, params);
			} 
			catch (IOException e) {
				machine.HandleMessage(MSGTYPE.UPDATE_IMAGE, false, params);
			}
			finally{
				db.close();
			}
		}
	}

	private void dologin(HashMap<String, String> params) {
		SQLiteDatabase db = MyHelper.get(machine).getReadableDatabase();
		if (db!=null){
			Cursor c=db.rawQuery( 
				     "SELECT _id FROM users WHERE email='"+
				    		 params.get("email")+"' AND passwd='"+
				    		 params.get("passwd")+"'", null);
			if (c.moveToFirst()){
				params.put("_id", c.getString(0));
				machine.HandleMessage(MSGTYPE.LOGIN, true, params);
			}
			else{
				machine.HandleMessage(MSGTYPE.LOGIN, false, null);				
			}
			c.close();
			db.close();
		}
	}

	private void doregister(HashMap<String, String> params) {
		SQLiteDatabase db = MyHelper.get(machine).getWritableDatabase();
		if (db!=null){
			Cursor c=db.rawQuery( 
				     "SELECT _id FROM users WHERE email='"+
				    		 params.get("email")+"'", null);
			if (c.moveToFirst()){
				params.put("_id", c.getString(0));
				machine.HandleMessage(MSGTYPE.REGISTER, false, params);
			}
			else{
				db.execSQL("INSERT INTO users (email, passwd,username)"+ 
						"VALUES ('"+params.get("email")+"', '"+params.get("passwd")+"','"+params.get("username")+"')"); 
				machine.HandleMessage(MSGTYPE.REGISTER, true, null);				
			}
			c.close();
			db.close();
		}
	}

}
